<template>
  <div class="box">
    <!-- 头部添加和搜索 -->
    <div class="head">
      <el-button type="primary" @click="add">添加用户</el-button>
      <el-input
        placeholder="请输入用户名"
        v-model="username"
        class="input-with-select"
      >
        <template slot="prepend">搜索</template>
        <el-button
          slot="append"
          icon="el-icon-search"
          @click="search"
        ></el-button>
      </el-input>
    </div>
    <!-- 表格组件 -->
    <my-table :data="tableData" :cols="cols">
      <!-- 指定slot插槽并获取传递的当前行数据 -->
      <template v-slot:status="{ row }">
        <el-switch
          v-model="row.mg_state"
          active-color="#13ce66"
          inactive-color="#ff4949"
          @change="tog(row)"
        >
        </el-switch>
      </template>
      <!-- 操作 -->
      <template v-slot:caozuo="{ row }">
        <el-button
          type="primary"
          icon="el-icon-edit"
          @click="bj(row)"
          v-an="'edit'"
        ></el-button>
        <el-button
          type="warning"
          icon="el-icon-setting"
          @click="jues(row)"
          v-an="'setting'"
        ></el-button>
        <el-button
          type="danger"
          icon="el-icon-delete"
          @click="del(row)"
          v-an="'delete'"
        ></el-button>
      </template>
    </my-table>

    <!-- 分页 -->
    <div class="fy">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageInfo.pagenum"
        :page-sizes="[1, 3, 6, 10]"
        :page-size="pageInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
    <!-- 添加用户模态框 -->
    <el-dialog title="新增用户" :visible.sync="dialogVisible" width="50%">
      <!-- 表单 -->
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="ruleForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="ruleForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="ruleForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="ruleForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="qadd">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑用户模态框 -->
    <el-dialog title="修改用户" :visible.sync="bjFlag" width="50%">
      <!-- 表单 -->
      <el-form
        :model="BjForm"
        :rules="rules1"
        ref="BjForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="BjForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="BjForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="BjForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="bjFlag = false">取 消</el-button>
        <el-button type="primary" @click="qBj">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色模态框 -->
    <el-dialog title="分配角色" :visible.sync="dialogVisible1" width="40%">
      <p>当前用户：{{ jInfo.username }}</p>
      <p style="margin: 20px auto">当前角色：{{ jInfo.role_name }}</p>
      <div>
        分配新角色
        <el-select v-model="value" placeholder="请选择">
          <el-option
            v-for="item in options"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible1 = false">取 消</el-button>
        <el-button type="primary" @click="qFp">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import MyTable from "../components/table.vue";
export default {
  name: "",
  components: {
    MyTable,
  },
  data() {
    return {
      cols: [
        {
          type: "index",
          label: "序号",
          width: "60px",
        },
        {
          prop: "username",
          label: "用户名",
        },
        {
          prop: "email",
          label: "邮箱",
        },
        {
          prop: "mobile",
          label: "电话",
        },
        {
          prop: "role_name",
          label: "角色",
        },
        {
          prop: "mg_state",
          label: "状态",
          slot: "status",
        },
        {
          label: "操作",
          slot: "caozuo",
        },
      ],
      username: "",
      pageInfo: {
        pagenum: 1, //当前页码
        pagesize: 3, //每页多少条
        query: "", //搜索关键字
      },
      total: 10, //总共多少条数据
      tableData: [], //用户列表
      dialogVisible: false, //添加用户模态框的状态
      bjFlag: false, //编辑用户模态框的状态
      dialogVisible1: false, //分配角色模态框的状态
      //添加用户的表单
      ruleForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      //   添加表单非空校验
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        email: [{ required: true, message: "请输入邮箱", trigger: "blur" }],
        mobile: [{ required: true, message: "请输入手机", trigger: "blur" }],
      },
      //   编辑表单非空校验
      rules1: {
        email: [{ required: true, message: "请输入邮箱", trigger: "blur" }],
        mobile: [{ required: true, message: "请输入手机", trigger: "blur" }],
      },
      // 修改用户的表单
      BjForm: {
        id: "",
        email: "",
        mobile: "",
        username: "",
      },
      // 角色信息
      jInfo: {},
      userId: "", //用户id
      options: [], //分配角色下拉列表
      value: "", //下拉框选中内容
      
    };
  },

  // 局部自定义指令
  directives:{
    an:{
      bind(el,binding){
        // 获取本地存的自定义按钮权限数组
        let arr=JSON.parse(localStorage.getItem('arr'))
        // 获取当前指令绑定的值，判断数组里面有没有
        let flag = arr.includes(binding.value)
        // 如果没有这个权限就删除按钮
        if(!flag){
          // 这里获取不到dom节点  使用nexttick又获取不到this  使用定时器等同步代码执行完直接删除
          setTimeout(()=>{
            el.parentNode.removeChild(el)
          })
        }
      }
    }
  },




  watch: {
    // 只要搜索框是空的默认渲染所有数据
    username(val) {
      console.log(val);
      if (val == "") {
        this.pageInfo.query = "";
        this.getUserList();
      }
    },
  },
  created() {
    let arr=['edit','delete'];   //自定义按钮权限数组 修改和删除
    localStorage.setItem('arr',JSON.stringify(arr))
    // 用户列表请求
    this.getUserList();
  },
  mounted() {},
  methods: {
    // 把请求封装成函数，因为要多次调用
    getUserList() {
      this.$store.dispatch("getUserList", this.pageInfo).then((res) => {
        this.pageInfo.pagenum = res.pagenum;
        this.total = res.total;
        this.tableData = res.users;
      });
    },
    // 每页多少条数据
    handleSizeChange(val) {
      this.pageInfo.pagesize = val;
      this.getUserList();
    },
    // 当前页数
    handleCurrentChange(val) {
      this.pageInfo.pagenum = val;
      this.getUserList();
    },
    // 搜索
    search() {
      this.pageInfo.query = this.username;
      this.getUserList();
    },
    // 弹出添加模态框
    add() {
      this.dialogVisible = true;
    },
    // 确认添加
    qadd() {
      // vuex异步请求
      this.$store.dispatch("add", this.ruleForm).then((res) => {
        if (res.status == 201) {
          // 成功的提示
          this.$message.success(res.msg);
          //   关闭添加的模态框
          this.dialogVisible = false;
          //   清空输入框内容
          this.ruleForm = { username: "", password: "", email: "", mobile: "" };
          //   渲染数据
          this.getUserList();
        }
      });
    },
    // 修改状态
    tog(obj) {
      console.log(obj);
      this.$store.dispatch("Status", obj).then((res) => {
        if (res.status == 200) {
          this.$message.success(res.msg);
          this.getUserList();
        }
      });
    },
    // 弹出编辑模态框
    bj(row) {
      this.bjFlag = true;
      this.BjForm = JSON.parse(JSON.stringify(row));
    },
    // 确认修改
    qBj() {
      this.$store.dispatch("modification", this.BjForm).then((res) => {
        if (res.status == 200) {
          this.$message.success(res.msg);
          this.getUserList();
          this.bjFlag = false;
        }
      });
    },
    // 删除用户信息
    del(row) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$store.dispatch("deleteUser", row).then((res) => {
            if (res.status == 200) {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.getUserList();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 弹出分配角色模态框
    jues(row) {
      this.dialogVisible1 = true;
      // 获取角色id
      this.userId = row.id;
      // 数据回填
      this.jInfo = row;
      // 获取所有角色信息
      this.$store.dispatch("getRoles").then((res) => {
        if (res.meta.status == 200) {
          this.options = res.data;
        }
      });
    },
    // 确认分配角色
    qFp() {
      this.$store
        .dispatch("qFpEoles", { userid: this.userId, role_id: this.value })
        .then((res) => {
          if (res.meta.status == 200) {
            this.$message.success(res.meta.msg);
            this.dialogVisible1 = false;
            this.getUserList();
          }
        });
    },
  },
};
</script>

<style scoped lang='scss'>
.head {
  margin-bottom: 20px;
}
.box {
  padding: 20px;
  background: white;
}
.input-with-select {
  width: 300px;
  margin-left: 20px;
}
.fy {
  text-align: center;
  margin-top: 20px;
}
</style>
